package com.dimples.dd.system.mapper;

import com.dimples.dd.common.pojo.PageResult;
import com.dimples.dd.mybatis.core.mapper.BaseMapperX;
import com.dimples.dd.mybatis.core.query.MPJLambdaWrapperX;
import com.dimples.dd.system.model.entity.Oauth2AuthorizationDO;
import com.dimples.dd.system.model.entity.Oauth2RegisteredClientDO;
import com.dimples.dd.system.model.query.OAuth2AccessTokenPageQuery;
import org.apache.ibatis.annotations.Mapper;

import java.time.LocalDateTime;

@Mapper
public interface Oauth2AuthorizationMapper extends BaseMapperX<Oauth2AuthorizationDO> {

    /**
     * 访问令牌分页(有效期内的)
     *
     * @param pageQuery pageQuery
     * @return PageResult
     */
    default PageResult<Oauth2AuthorizationDO> selectPage(OAuth2AccessTokenPageQuery pageQuery) {
        MPJLambdaWrapperX<Oauth2AuthorizationDO> mpjLambdaWrapper = new MPJLambdaWrapperX<>();
        mpjLambdaWrapper.leftJoin(Oauth2RegisteredClientDO.class, Oauth2RegisteredClientDO::getId, Oauth2AuthorizationDO::getRegisteredClientId);
        mpjLambdaWrapper.selectAll(Oauth2AuthorizationDO.class)
                .selectAs(Oauth2RegisteredClientDO::getClientId, Oauth2AuthorizationDO::getRegisteredClientId);

        mpjLambdaWrapper.eqIfPresentOther(Oauth2RegisteredClientDO::getClientId, pageQuery.getClientId());
        mpjLambdaWrapper.eqIfPresent(Oauth2AuthorizationDO::getAuthorizationGrantType, pageQuery.getAuthorizationGrantType())
        ;
        mpjLambdaWrapper
                .eqIfPresent(Oauth2AuthorizationDO::getPrincipalName, pageQuery.getUsername())
                .gt(Oauth2AuthorizationDO::getAccessTokenExpiresAt, LocalDateTime.now())
                .orderByDesc(Oauth2AuthorizationDO::getId);
        return this.selectJoinPage(pageQuery, Oauth2AuthorizationDO.class, mpjLambdaWrapper);
    }
}